package cn.itcast.filters;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 字符编码过滤器
 */
public class CharsetEncodingFilter implements Filter {
    private String encoding;

    private boolean forceRequestEncoding = false;
    private boolean forceResponseEncoding = false;

    @Override
    public void init(FilterConfig config) throws ServletException {
        String encoding = config.getInitParameter("encoding");
        if (encoding != null && encoding.trim() != "") {
            this.encoding = encoding;
        }

        boolean force = Boolean.valueOf(config.getInitParameter("force"));
        forceRequestEncoding = force;
        forceResponseEncoding = force;

        System.out.println(getClass().getSimpleName() + "# Encoding: " + encoding + " Force: " + force);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        System.out.println(getClass().getSimpleName() + "# 飘过～");

        String encoding = getEncoding();
        if (encoding != null) {
            if (isForceRequestEncoding() || request.getCharacterEncoding() == null) {
                request.setCharacterEncoding(encoding);
            }
            if (isForceResponseEncoding()) {
                response.setCharacterEncoding(encoding);
            }
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        System.out.println("Destory: " + this.getClass().getSimpleName());
    }

    public String getEncoding() {
        return encoding;
    }

    public boolean isForceRequestEncoding() {
        return forceRequestEncoding;
    }

    public boolean isForceResponseEncoding() {
        return forceResponseEncoding;
    }
}
